package com.code.test.first.tree;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * https://leetcode.cn/problems/n-ary-tree-level-order-traversal/description/
 * 给定一个 N 叉树，返回其节点值的层序遍历。 (即从左到右，逐层遍历)。
 */
public class Code429 {

    public static void main(String[] args) {
        TreeNode left10 = new TreeNode(10, null, null);
        TreeNode right20 = new TreeNode(20, null, null);
        TreeNode left30 = new TreeNode(15, null, null);
        TreeNode right40 = new TreeNode(7, null, null);
        TreeNode left3 = new TreeNode(9, null,null);
        TreeNode right5 = new TreeNode(20, left30, right40);
        TreeNode root = new TreeNode(3, left3, right5);

        List<List<Integer>> ret = levelOrder(root);
        System.out.println(ret);
    }


    /**
     * 差别只在于孩子是多叉树
     * @param root
     * @return
     */
    public static List<List<Integer>> levelOrder(TreeNode root) {

        Queue<TreeNode> queue = new LinkedList<>();
        List<List<Integer>> ret = new ArrayList<>();

        queue.add(root);
        while (!queue.isEmpty()) {

            //这里是每一层的大小，直接圈定好，循环里面再加是为了下一次做准备
            int len = queue.size();
            List<Integer> cur = new ArrayList<>();
            for (int i = 0; i < len; i++) {
                TreeNode node = queue.poll();
                cur.add(node.val);
                if (node.left != null) {
                    queue.add(node.left);
                }
                if (node.right != null) queue.add(node.right);
            }
            ret.add(cur);
        }
        return ret;
    }

}
